package cn.stylefeng.guns.modular.yingbao.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.yingbao.entity.*;
import cn.stylefeng.guns.modular.yingbao.handler.BuildingHandler;
import cn.stylefeng.guns.modular.yingbao.mapper.SysBuildingMapper;
import cn.stylefeng.guns.modular.yingbao.model.params.SysBuildingParam;
import cn.stylefeng.guns.modular.yingbao.model.result.SysBuildingResult;
import cn.stylefeng.guns.modular.yingbao.service.*;
import cn.stylefeng.guns.modular.yingbao.util.DateUtils;
import cn.stylefeng.guns.modular.yingbao.util.RandomNum;
import cn.stylefeng.guns.modular.yingbao.util.StringUtil;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.apache.bcel.generic.IF_ACMPEQ;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 建仓订单表 服务实现类
 * </p>
 *
 * @author jj
 * @since 2019-12-18
 */
@Service
public class SysBuildingServiceImpl extends ServiceImpl<SysBuildingMapper, SysBuilding> implements SysBuildingService {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    UserMoneyService userMoneyService;

    @Autowired
    UserMoneyLogService userMoneyLogService;

    @Autowired
    SysGroupLogService sysGroupLogService;

    @Autowired
    ContractSettingService contractSettingService;

    @Lazy
    @Autowired
    BuildingHandler buildingHandler;

    @Autowired
    SysUserGroupService sysUserGroupService;

    @Override
    public synchronized ResponseData building(Long userid, Long price) {
        if (userid==null || price==null){
            return ResponseData.error("参数错误！");
        }
        SysBuilding sysBuilding=new SysBuilding();
        ResponseData test = test(userid, price,sysBuilding);
        if(test != null){
            return test;
        }
        buildingHandler.building(sysBuilding);
        buildingHandler.promotion(sysBuilding);
        return  ResponseData.success(200,"成功",null);
    }

    @Transactional(rollbackFor = Exception.class,timeout = 360)
    public ResponseData test(Long userid, Long price,SysBuilding sysBuilding){
        Long price1=price*100;

        List<SysBuilding> sysBuildings = this.baseMapper.selectList(new QueryWrapper<SysBuilding>().eq("userid", userid).eq("stuats", 1));
        if (sysBuildings.size()>0){
            return ResponseData.error("建仓订单中，只能执行一手合约");
        }
        SysUser sysUser = sysUserService.getById(userid);
        if (sysUser ==null){
            return ResponseData.error("未找到该用户");
        }
        if ("2".equals(sysUser.getStatus())){
            return ResponseData.error("您的账户已被冻结！请及时联系客服");
        }

        UserMoney userMoney = userMoneyService.getOne(new QueryWrapper<UserMoney>().eq("userid", userid));
        if (userMoney==null){
            return ResponseData.error("查询余额异常");
        }
        if (userMoney.getCabinMoney()<price1){
            return ResponseData.error("可用余额不足");
        }

        QueryWrapper<ContractSetting> query =new  QueryWrapper();
        if (sysUser.getIsNewbie()==1){
            query.eq("contract_type",0);
        }else {
            query.in("contract_type",1,2,3);
        }
        query.le("price",price1);
        query.ge("price1",price1);
        query.orderByAsc("price1");
        List<ContractSetting> list = contractSettingService.list(query);
        if (list == null||list.size()<1){
            return ResponseData.error("不可超出合约区间");
        }
        ContractSetting contractSetting=list.get(0);

        Long vipId = sysUser.getVipId();
        if (vipId==1){
            Long buyingVipTime = contractSetting.getBuyingVipTime()/60/60;
            sysBuilding.setBuildingTime(DateUtils.addDateMinut(new Date(),buyingVipTime.intValue()));
            sysBuilding.setFate(buyingVipTime.intValue());
            sysBuilding.setIsVip(1);
        }else {
            Long buyingTime = contractSetting.getBuyingTime()/60/60;
            sysBuilding.setBuildingTime(DateUtils.addDateMinut(new Date(),buyingTime.intValue()));
            sysBuilding.setFate(buyingTime.intValue());
            sysBuilding.setIsVip(0);
        }

        SysUserGroup sysUserGroup = sysUserGroupService.getOne(new QueryWrapper<SysUserGroup>().eq("userid", userid));
        if (sysUser.getIsNewbie()==1){
            sysUser.setIsNewbie(0);
            long version = sysUser.getVersion();
            sysUser.setVersion(version+1);
            sysUserService.update(sysUser, new QueryWrapper<SysUser>().eq("id", sysUser.getId()).eq("version", version));

            sysUserGroup.setIsNewbie(0);
        }
        sysUserGroup.setGroupOrdinalSize(1L);
        sysUserGroup.setOrdinalSize(sysUserGroup.getOrdinalSize()+1);
        sysUserGroup.setTeamId("");
        sysUserGroup.setMoney(0L);
        sysUserGroup.setGrade(0);
        int version1 = sysUserGroup.getVersion();
        sysUserGroup.setVersion(version1+1);
        boolean update1 = sysUserGroupService.update(sysUserGroup, new QueryWrapper<SysUserGroup>().eq("id", sysUserGroup.getId()).eq("version", version1));
        if (!update1){
            throw new UnsupportedOperationException("建仓记录添加失败！");
        }
        sysBuilding.setReferrerId(sysUserGroup.getReferrerId());
        sysBuilding.setSjReferrerId(sysUserGroup.getSjReferrerId());
        sysBuilding.setPrice(price1);
        sysBuilding.setUserid(userid);
        sysBuilding.setEarnings(Long.valueOf(contractSetting.getEarnings()));
        sysBuilding.setOrdinal(RandomNum.getUUID_16());
        sysBuilding.setStuats("1");
        sysBuilding.setVersion(0);
        sysBuilding.setType(contractSetting.getContractType());
        sysBuilding.setMoney(price1*sysBuilding.getEarnings()/100);
        sysBuilding.setCreateTime(new Date());
        int insert = baseMapper.insert(sysBuilding);
        if (insert<1){
            throw new UnsupportedOperationException("建仓失败！");
        }
        userMoney.setCabinMoney( userMoney.getCabinMoney()-price1);
        long version = userMoney.getVersion();
        userMoney.setVersion(version+1);
        boolean update = userMoneyService.update(userMoney, new QueryWrapper<UserMoney>().eq("id", userMoney.getId()).eq("version", version));
        if (!update){
            return ResponseData.error("金额更新错误！");
        }
        return null;
    }
    @Override
    public ResponseData buildingLook(Long userid, String ordinal,String stuats) {
        if (userid==null || StringUtils.isEmpty(ordinal)||StringUtils.isEmpty(stuats)){

            return ResponseData.error("参数错误！");
        }
        SysBuilding sysBuilding = baseMapper.selectOne(new QueryWrapper<SysBuilding>().eq("userid", userid)
                .eq("ordinal", ordinal).eq("stuats", stuats));
        return sysBuilding != null ? ResponseData.success(200,"成功",sysBuilding): ResponseData.error("暂无数据");
    }

    @Override
    public ResponseData buildingListLook(Long userid, String stuats) {

        if (userid==null || StringUtils.isEmpty(stuats)){
            return ResponseData.error("参数错误！");
        }
        List<SysBuilding> sysBuilding = baseMapper.selectList(new QueryWrapper<SysBuilding>().eq("userid", userid).eq("stuats", stuats).orderByDesc("create_time"));
        return sysBuilding != null ? ResponseData.success(200,"成功",sysBuilding): ResponseData.error("暂无数据");
    }

    @Override
    public ResponseData groupEarnings(Long userid, int pageNum, int pageSize) {

        if (userid==null ){
            return ResponseData.error("参数错误！");
        }

        IPage<SysGroupLog> sysGroupLogIPage = sysGroupLogService.page(new Page<>(pageNum, pageSize), new QueryWrapper<SysGroupLog>().eq("userid",userid).orderByDesc("create_time"));

        return sysGroupLogIPage.getTotal() > 0 ?ResponseData.success(200,"成功",sysGroupLogIPage):ResponseData.error("暂无数据");
    }

    @Override
    public ResponseData group(Long userid) {

        if (userid==null ){
            return ResponseData.error("参数错误！");
        }
        SysUserGroup sysUserGroup = sysUserGroupService.getOne(new QueryWrapper<SysUserGroup>().eq("userid", userid));
        if (sysUserGroup==null){
            return  ResponseData.error("数据错误！");
        }
        return ResponseData.success(200,"成功",sysUserGroup);
    }

    @Override
    public void updateBuilding() {
        Date date = new Date();
        List<SysBuilding> sysBuildings = this.baseMapper.selectList(new QueryWrapper<SysBuilding>().lt("building_time", date).eq("stuats","1"));
        sysBuildings.forEach(m -> {
            buildingHandler.buildingHandler1(m);
        });
    }


    @Override
    public void add(SysBuildingParam param){
        SysBuilding entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(SysBuildingParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(SysBuildingParam param){
        SysBuilding oldEntity = getOldEntity(param);
        SysBuilding newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public SysBuildingResult findBySpec(SysBuildingParam param){
        return null;
    }

    @Override
    public List<SysBuildingResult> findListBySpec(SysBuildingParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(SysBuildingParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }



    private Serializable getKey(SysBuildingParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private SysBuilding getOldEntity(SysBuildingParam param) {
        return this.getById(getKey(param));
    }

    private SysBuilding getEntity(SysBuildingParam param) {
        SysBuilding entity = new SysBuilding();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
